let Room = require("../data/Room.class");
let EventListener = require("../core/EventListener.class");
let MessageId = require("./MessageId");
let RoomController = require("../controller/RoomController.class");
let CardController = require("../controller/CardController.class");

class zjhRoom extends Room{
    constructor(data){
        data.maxPlayer = 5;
        super(data);
        let self = this;
        self.base_score = 1;
        self.bi_round = 0;
        self.kan_round = 0;
        self.cur_round = 0;
        self.max_round = 10;
        self.cur_beishu = 1;
        self.max_beishu = 5;
        self.operation = {qi: 0, bi: 1, jia: 2, gen: 3, kan: 4, pklist: 5};

        /*
        *  所有可以操作的玩家都在这个数组中
        * （0）拥有手牌玩家的uid都存放在改数组中
        * （1）比牌输，从数组中移除
        * （2）玩家弃牌，从数组中移除
        * （3）数组长度为1时，本局结束，该数组清空
        * */
        self.operationUids = [];

        EventListener.getInstance().addListener(this.className, MessageId.Operation, function (data) {
            if (data["beishu"]){
                self.cur_beishu = data["beishu"];
            }
            // 操作广播
            let player = self.getPlayerByUid(data["uid"]);
            let messageObj = {};
            switch (data["operation"]){
                case self.operation.qi:
                    // 1、从操作者列表中移除
                    self.removeOperator(data.uid);

                    // 2、广播玩家弃牌，所有的玩家都应改知晓
                    messageObj.code = MessageId.OperationBroadcast;
                    messageObj.data = data;
                    RoomController.getInstance().broadcast(self.players, messageObj);
                    break;
                case self.operation.bi:
                    self.onBi(data);
                    break;
                case self.operation.jia:
                    break;
                case self.operation.gen:
                    break;
                case self.operation.kan:
                    // 1、更新看牌状态
                    // let player = self.getPlayerByUid(data.uid);
                    player.setKan(true);
                    // 2、广播看牌
                    let obj = {};
                    for (let i = 0; i < self.players.length; i++){
                        let messageObj = {};
                        messageObj.code = MessageId.OperationBroadcast;
                        messageObj.data = {};
                        for (let key in data){
                            messageObj.data[key] = data[key];
                        }
                        let player = self.players[i];
                        if(player.getUid() === data.uid){
                            messageObj.data.cardArr = player.getCards();
                            console.log("operation kan uid = " + player.getUid() + " | cards = " + JSON.stringify(messageObj.data.cardArr));
                        }
                        obj[player.getUid()] = messageObj;
                    }
                    RoomController.getInstance().broadcastArr(obj);
                    break;
                default:
                    break;
            }

            // 2、游戏是否结束
            if (self.isGameOver()){
                console.log("本局游戏结束了...");
                // 2.1、算分处理、及结算广播
                self.onSettlement();
                // 2.2、判断是否总结算，没有总结算进入下一局
                if (self.curentRound === self.totalRound) {
                    self.onTotalSettlement();
                } else {
                    self.nextRound();
                }
            } else {
                if (data.operation !== self.operation.kan) {
                    self.turnSeat++;
                }
                self.onTurn();
            }
        });
    }
    shuffle(){
        let self = this;
        CardController.getInstance().shuffle(self.players);
    }
    dealCards(){
        let self = this;
        let messageObj = {};
        messageObj.code = MessageId.DealCards;
        messageObj.data = {};
        RoomController.getInstance().broadcast(self.players, messageObj);

        // 清空并生成可操作玩家uid数组
        self.operationUids = [];
        for (let i = 0; i < self.players.length; i++){
            self.operationUids.push(self.players[i].getUid());
        }
        console.log("可操作玩家uid数组："+self.operationUids.join(","));
    }
    // 比牌处理
    onBi(data){
        // 1、bi_uid为0，如果可操作列表长度为2，直接比牌，如果可操作数组长度大于2，则返回可比牌玩家的uid数组
        // 2、bi_uid不为0，返回可比牌玩家uid数组
        let self = this;
        let uid = data["uid"];
        let bi_uid = data["bi_uid"];
        let  messageObj = {};
        let bifunc = function (bi_uid) {
            let player = self.getPlayerByUid(uid);
            let bi_player = self.getPlayerByUid(bi_uid);
            let result = CardController.getInstance().pkCards(player.getCards(), bi_player.getCards());

            // 1、将输家踢出操作者列表
            let winner_uid = result.iswin? player.getUid(): bi_player.getUid();
            let loser_uid = !result.iswin? player.getUid(): bi_player.getUid();
            self.removeOperator(loser_uid);

            // 2、广播比牌
            player.setCardType(result.card_type[0]);
            player.setWin(result.iswin);
            bi_player.setCardType(result.card_type[1]);
            bi_player.setWin(!result.iswin);
            messageObj.code = MessageId.OperationBroadcast;
            messageObj.data = {};
            messageObj.data["winner_uid"] = winner_uid;
            for (let key in data) {
                messageObj.data[key] = data[key];
            }
            messageObj.data["bi_uid"] = bi_uid;
            RoomController.getInstance().broadcast(self.players, messageObj);
        };

        if (bi_uid === 0) {
            if (this.operationUids.length === 2) {
                for (let i = 0; i < self.operationUids.length; i++){
                    if (self.operationUids[i] !== uid){
                        bi_uid = self.operationUids[i];
                    }
                }
                bifunc(bi_uid);
            } else {
                messageObj.code = MessageId.OperationPk;
                messageObj.data = {};
                messageObj.data.operation = self.operation.pklist;
                messageObj.data.uid = data.uid;
                messageObj.data.bi_arr = [];
                for (let i = 0; i < self.operationUids.length; i++) {
                    if (self.operationUids[i] !== uid){
                        messageObj.data.bi_arr.push(self.operationUids[i]);
                    }
                }
                RoomController.getInstance().synchronous({uid: data.uid, messageObj: messageObj});
            }
        } else {
            bifunc(data["bi_uid"]);
        }
    }
    // 移除操作者
    removeOperator(uid){
        let index = this.operationUids.indexOf(uid);
        if (index > -1) {
            this.operationUids.splice(index, 1);
        } else {
            console.log("没有在操作者数组【"+this.operationUids.join(",")+"】找到uid【" + uid + "】");
        }
    }
    onTurn(){
        let self = this;
        if (self.turnSeat >= self.players.length) {
            self.turnSeat = 0;
            self.cur_round++;
        }

        let player = self.getPlayerBySeat(self.turnSeat);
        let messageObj = {};
        messageObj.code = MessageId.Operation;
        messageObj.data = {};
        messageObj.data.can_qi = true;
        messageObj.data.can_kan = !player.isKan() && self.cur_round >= self.kan_round ;
        messageObj.data.can_bi = self.cur_round >= self.bi_round;
        messageObj.data.can_jia = self.cur_beishu < self.max_beishu;
        messageObj.data.can_gen = true;
        messageObj.data.zhu_list = [2,3,4,5];
        for (let i = 0; i < messageObj.data.zhu_list.length; i++){
            if (messageObj.data.zhu_list[i] > self.cur_beishu){
                break;
            }
            messageObj.data.zhu_list[i] *= -1;
        }
        messageObj.data.bi_score = self.cur_beishu * self.base_score * player.getBeiShu();
        messageObj.data.jia_score = self.cur_beishu * self.base_score * player.getBeiShu();
        messageObj.data.gen_score = self.cur_beishu * self.base_score * player.getBeiShu();
        messageObj.data.uid = self.getUidBySeat(self.turnSeat);
        RoomController.getInstance().broadcast(self.players, messageObj);
        console.log("当前操作的玩家【"+self.turnSeat+"】");
    }
    isGameOver(){
        return this.operationUids.length === 1;
    }
    onSettlement(){
        let messageObj = {};
        messageObj.code = MessageId.Settlement;
        messageObj.data = {};
        RoomController.getInstance().broadcast(this.players, messageObj);
    }
    onTotalSettlement(){

    }
    clearData(){
        let self = this;
        self.base_score = 1;
        self.bi_round = 0;
        self.kan_round = 0;
        self.cur_round = 0;
        self.max_round = 10;
        self.cur_beishu = 1;
        self.max_beishu = 5;
        self.operationUids = [];
        for (let i = 0; i < self.players.length; i++){
            self.players[i].setKan(false);
        }
    }
}
module.exports = zjhRoom;